<script>
import { h } from 'vue';

export default {
  name: 'map-core-2.0',
  props: {
    mapKey: { type: String, default: 'd99cf0fc41f79425572e5b1298c0f21c' },
    mapStyle: { type: String, default: 'amap://styles/cfd800a417c5e6683065b909ce2cee62' },
    mapOptions: { type: Object, default: undefined },
  },
  data() {
    return {
      id: 'map-container-' + Date.now(),
      visible: false,
      ready: false,
    };
  },
  mounted() {
    let _this = this;
    window.onAMapApiLoaded = function () {
      let { mapOptions } = _this;
      if (typeof mapOptions === 'function') {
        mapOptions = mapOptions();
      }
      let opt = {
        mapStyle: _this.mapStyle,
        expandZoomRange: true,
        zooms: [3, 24],
        viewMode: '3D',
        pitch: 55,
        zoom: 9,
      };
      _this.map = new AMap.Map(_this.id, Object.assign({}, opt, mapOptions));
      _this.scope = {
        map: _this.map,
        mapGetter: () => _this.map,
      };
      _this.ready = true;
      _this.map.on('complete', () => {
        _this.$emit('ready', _this.scope);
      });
      setTimeout(() => {
        _this.visible = true;
      }, 300);
      delete window.onAMapApiLoaded;
    };
    const url = 'https://webapi.amap.com/maps?v=2.0&key=' + this.mapKey + '&callback=onAMapApiLoaded';
    const jsapi = document.createElement('script');
    jsapi.charset = 'utf-8';
    jsapi.src = url;
    document.head.appendChild(jsapi);
  },
  render() {
    return h('div', { class: 'map-core map-core-2.0' }, [
      h('div', { id: this.id, class: 'map-container', style: { visibility: this.visible ? 'visible' : 'hidden' } }),
      this.ready === true && this.$slots.default ? this.$slots.default(this.scope) : null,
    ]);
  },
};
</script>

<style>
.amap-logo,
.amap-copyright {
  display: none !important;
}
</style>
<style scoped lang="less">
.map-core {
  position: relative;
  width: 100%;
  height: 100%;
  .map-container {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: 0;
    overflow: hidden;
    transition: opacity ease 1s;
  }
}
</style>
